//
//  ZFHttpTool.m
//  HappilyLoan
//
//  Created by zainishenbian on 2017/3/20.
//  Copyright © 2017年 zongqingxiangqian. All rights reserved.
//

#import "ZFHttpTool.h"
#import "MD5Util.h"
#import "ZFHeader.h"

//#define PUBLIC_KEY @"040CD66A84025B94CEAC3EC1B49C92D0"
//#define APP_KEY    @"ZQXQ-XYJD"
//#define UDID       [[NSUserDefaults standardUserDefaults] objectForKey:@"UDID"]
//#define APP_VERSION  @"1.0.1"

@implementation ZFHttpTool

//多图上传,身份认证
+ (void)uploadImageWithURL:(NSString *)url params:(NSDictionary *)params imgArray:(NSArray *)array bodyStr:(NSString *)bodyStr success:(void(^)(id responseObject))success failure:(void(^)(NSError *error))failure;
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = nil;
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.securityPolicy = [AFSecurityPolicy defaultPolicy];
    manager.securityPolicy.allowInvalidCertificates = YES;
    manager.securityPolicy.validatesDomainName = NO;
    manager.requestSerializer.timeoutInterval = 10;
    
    /*******************设置请求头***************************/
    //参数utf8编码
    NSString *bodyUTF8 = [bodyStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"------%@",bodyUTF8);
    if ([bodyStr isEqualToString:@""]) {
        
        bodyUTF8 = @"";
    }
    //获取当前时间戳
    NSString *timestamp = [ZFPulicAPI getCurrentTimestamp];
    //签名信息
    NSString *signatureStr = [NSString stringWithFormat:@"%@%@%@%@%@%@%@%@",PUBLIC_KEY,APP_KEY,SOURCE,CHANNEL,CLIENT_ID,APP_VERSION,bodyUTF8,timestamp];
    NSString *signatureMD5 = [MD5Util md5:signatureStr];
    
    [manager.requestSerializer setValue:PUBLIC_KEY forHTTPHeaderField:@"public_key"];
    [manager.requestSerializer setValue:APP_KEY forHTTPHeaderField:@"app_key"];
    [manager.requestSerializer setValue:SOURCE forHTTPHeaderField:@"source"];
    [manager.requestSerializer setValue:CLIENT_ID forHTTPHeaderField:@"client_id"];
    [manager.requestSerializer setValue:CHANNEL forHTTPHeaderField:@"channel"];
    [manager.requestSerializer setValue:APP_VERSION forHTTPHeaderField:@"app_version"];
    [manager.requestSerializer setValue:timestamp forHTTPHeaderField:@"timestamp"];
    [manager.requestSerializer setValue:signatureMD5 forHTTPHeaderField:@"signature"];

    NSArray *imgKey = @[@"face_photo_file",@"idcard_front_file",@"idcard_back_file"];

    [manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        for (int i = 0; i < array.count; i ++) {
            
            [formData appendPartWithFileData:array[i] name:imgKey[i] fileName:[NSString stringWithFormat:@"%d.jpg",i] mimeType:@"image/jpeg"];
        }
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (success)
        {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            success(dict);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (failure)
        {
            failure(error);
        }
    }];

}
+ (void)postWithURL:(NSString *)url params:(NSDictionary *)params success:(void(^)(id responseObject))success failure:(void(^)(NSError *error))failure
{
    // 创建请求管理对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = nil;
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.securityPolicy = [AFSecurityPolicy defaultPolicy];
    manager.securityPolicy.allowInvalidCertificates = YES;
    manager.securityPolicy.validatesDomainName = NO;
    manager.requestSerializer.timeoutInterval = 10;
    
    //HTTPS SSL的验证，
    //    [manager setSecurityPolicy:[ZFHttpTool customSecurityPolicy]];
    //请求
    [manager POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (success)
        {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            success(dict);
        }
    }
    failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure)
        {
            failure(error);
        }
    }];
}
+ (void)postWithURL:(NSString *)url params:(NSDictionary *)params bodyStr:(NSString *)bodyStr success:(void(^)(id responseObject))success failure:(void(^)(NSError *error))failure
{
    // 创建请求管理对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = nil;
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.securityPolicy = [AFSecurityPolicy defaultPolicy];
    manager.securityPolicy.allowInvalidCertificates = YES;
    manager.securityPolicy.validatesDomainName = NO;
    manager.requestSerializer.timeoutInterval = 10;
    
    /*******************设置请求头***************************/
    //参数utf8编码
    NSString *bodyUTF8 = [bodyStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    bodyUTF8 = [ZFHttpTool blankEncode:bodyUTF8];
    if ([bodyStr isEqualToString:@""]) {
        
        bodyUTF8 = @"";
    }
    if ([url isEqualToString:[NSString stringWithFormat:@"%@/archives/postUserUrgentInfo",SERVERIP]]) {
        
        bodyUTF8 = bodyStr;
    }
    //获取当前时间戳
    NSString *timestamp = [ZFPulicAPI getCurrentTimestamp];
    //签名信息
    NSString *signatureStr = [NSString stringWithFormat:@"%@%@%@%@%@%@%@%@",PUBLIC_KEY,APP_KEY,SOURCE,CHANNEL,CLIENT_ID,APP_VERSION,bodyUTF8,timestamp];
    NSString *signatureMD5 = [MD5Util md5:signatureStr];
    
    [manager.requestSerializer setValue:PUBLIC_KEY forHTTPHeaderField:@"public_key"];
    [manager.requestSerializer setValue:APP_KEY forHTTPHeaderField:@"app_key"];
    [manager.requestSerializer setValue:SOURCE forHTTPHeaderField:@"source"];
    [manager.requestSerializer setValue:CLIENT_ID forHTTPHeaderField:@"client_id"];
    [manager.requestSerializer setValue:CHANNEL forHTTPHeaderField:@"channel"];
    [manager.requestSerializer setValue:APP_VERSION forHTTPHeaderField:@"app_version"];
    [manager.requestSerializer setValue:timestamp forHTTPHeaderField:@"timestamp"];
    [manager.requestSerializer setValue:signatureMD5 forHTTPHeaderField:@"signature"];

    //HTTPS SSL的验证，
    //    [manager setSecurityPolicy:[ZFHttpTool customSecurityPolicy]];
    //请求
    [manager POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (success)
        {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            success(dict);
        }
    }
    failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
              if (failure)
              {
                  failure(error);
              }
          }];

}
//+ (void)postXmlWithURL:(NSString *)url params:(NSDictionary *)params success:(void(^)(id responseObject))success failure:(void(^)(NSError *error))failure
//{
//    // AFNetWorking
//    // 创建请求管理对象
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    //NSDictionary *params = @{@"format": @"xml"};
//    // 发生请求
//    [manager POST:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        if (success) {
//            success(responseObject);
//        }
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        if (failure) {
//            failure(error);
//        }
//    }];
//
//
//}

//+ (void)postWithURL:(NSString *)url params:(NSDictionary *)params formDataArray:(NSArray *)formDataArray success:(void (^)(id))success failure:(void (^)(NSError *))failure
//{
//    // AFNetWorking
//    // 创建请求管理对象
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
//    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//
//    // 发送请求
//    [manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> allFormData) {
//        for (VTFormData *formData in formDataArray) {
//            [allFormData appendPartWithFileData:formData.data name:formData.name fileName:formData.filename mimeType:formData.mimeType];
//        }
//    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        if (success) {
//            NSData *data = [[NSData alloc]initWithData:[operation.responseString dataUsingEncoding:NSUTF8StringEncoding]];
//            id dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
//            success(dic);
//        }
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        if (failure) {
//            failure(error);
//        }
//    }];
//}

+ (void)getWithURL:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    // 创建请求管理对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = nil;
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.securityPolicy = [AFSecurityPolicy defaultPolicy];
    manager.securityPolicy.allowInvalidCertificates = YES;
    manager.securityPolicy.validatesDomainName = NO;
    manager.requestSerializer.timeoutInterval = 10;
    
    //HTTPS SSL的验证，
    //    [manager setSecurityPolicy:[ZFHttpTool customSecurityPolicy]];
    //请求
    [manager GET:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (success)
        {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            success(dict);
        }
    }
    failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        if (failure)
        {
            failure(error);
        }
    }];
    // 创建请求管理对象
    //    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    //    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    //    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //
    //    // 发生请求
    //    [manager GET:url parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
    //        if (success) {
    //            NSData *data = [[NSData alloc]initWithData:[operation.responseString dataUsingEncoding:NSUTF8StringEncoding]];
    //            id dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    //            success(dic);
    //        }
    //    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    //        if (failure) {
    //            failure(error);
    //        }
    //    }];
}
//证书验证
+ (AFSecurityPolicy *)customSecurityPolicy
{
    //先导入证书，找到证书的路径
    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"Admin" ofType:@"cer"];
    NSData *certData = [NSData dataWithContentsOfFile:cerPath];
    
    //AFSSLPinningModeCertificate 使用证书验证模式
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
    
    //allowInvalidCertificates 是否允许无效证书（也就是自建的证书），默认为NO
    //如果是需要验证自建证书，需要设置为YES
    securityPolicy.allowInvalidCertificates = YES;
    
    //validatesDomainName 是否需要验证域名，默认为YES；
    //假如证书的域名与你请求的域名不一致，需把该项设置为NO；如设成NO的话，即服务器使用其他可信任机构颁发的证书，也可以建立连接，这个非常危险，建议打开。
    //置为NO，主要用于这种情况：客户端请求的是子域名，而证书上的是另外一个域名。因为SSL证书上的域名是独立的，假如证书上注册的域名是www.google.com，那么mail.google.com是无法验证通过的；当然，有钱可以注册通配符的域名*.google.com，但这个还是比较贵的。
    //如置为NO，建议自己添加对应域名的校验逻辑。
    securityPolicy.validatesDomainName = NO;
    NSSet *set = [[NSSet alloc] initWithObjects:certData, nil];
    securityPolicy.pinnedCertificates = set;
    
    return securityPolicy;
}
#pragma mark ———— 参数按顺序拼接
+ (NSString *)sortBodyStr:(NSDictionary *)bodyParameter
{
    NSArray *allKeys = [bodyParameter allKeys];
    NSArray *resultArray = [allKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    
    NSString *bodyStr = nil;
    if (resultArray.count == 1) {
        
        bodyStr = [NSString stringWithFormat:@"%@=%@",resultArray[0],bodyParameter[resultArray[0]]];
    }
    else
    {
        bodyStr = [NSString stringWithFormat:@"%@=%@&",resultArray[0],bodyParameter[resultArray[0]]];

    }
    for (int i = 1; i < resultArray.count; i ++) {
        
        NSString *appendingStr = nil;
        if (i < resultArray.count-1) {
            
            appendingStr = [NSString stringWithFormat:@"%@=%@&",resultArray[i],bodyParameter[resultArray[i]]];
        }
        else
        {
            appendingStr = [NSString stringWithFormat:@"%@=%@",resultArray[i],bodyParameter[resultArray[i]]];
        }
        bodyStr = [bodyStr stringByAppendingString:appendingStr];
    }
    
    return bodyStr;
}
//空格编码（+，%20）
+ (NSString *)blankEncode:(NSString *)str
{
    return [str stringByReplacingOccurrencesOfString:@"%20" withString:@"+"];
}

@end

@implementation VTFormData

@end
